//
//  ViewController.m
//  LearnBluetooth
//
//  Created by ShortHair on 15/3/29.
//  Copyright (c) 2015年 Short Hair. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController ()<CBCentralManagerDelegate, CBPeripheralDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) CBCentralManager *manager;
@property (nonatomic, strong) NSMutableArray *peripherals;
@property (nonatomic, weak) CBPeripheral *connectedPeripheral;
@property (nonatomic, assign) BOOL connecting;

#pragma mark -UIs
@property (nonatomic, weak) IBOutlet UIView *noBluetoothView;
@property (nonatomic, weak) IBOutlet UILabel *stateLabel;
@property (nonatomic, weak) IBOutlet UITableView *peripheralTable;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //建立存储数组
    self.peripherals = [NSMutableArray array];
    //建立中心角色
    self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    //扫描
    NSDictionary *options = @{CBCentralManagerScanOptionAllowDuplicatesKey: @YES};
    [self.manager scanForPeripheralsWithServices:nil options:options];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    [self.noBluetoothView setHidden:(central.state == CBCentralManagerStatePoweredOn)];
    if(central.state == CBCentralManagerStatePoweredOn)
    {
        NSDictionary *options = @{CBCentralManagerScanOptionAllowDuplicatesKey: @YES};
        [self.manager scanForPeripheralsWithServices:nil options:options];
    }
    else
    {
        [self.manager stopScan];
    }
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            self.stateLabel.text = @"CBCentralManagerStateUnknown";
            break;
        case CBCentralManagerStateResetting:
            self.stateLabel.text = @"CBCentralManagerStateResetting";
            break;
        case CBCentralManagerStateUnsupported:
            self.stateLabel.text = @"CBCentralManagerStateUnsupported";
            break;
        case CBCentralManagerStateUnauthorized:
            self.stateLabel.text = @"CBCentralManagerStateUnauthorized";
            break;
        case CBCentralManagerStatePoweredOff:
            self.stateLabel.text = @"CBCentralManagerStatePoweredOff";
            break;
        case CBCentralManagerStatePoweredOn:
            self.stateLabel.text = @"CBCentralManagerStatePoweredOn";
            break;
        default:
            break;
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    if ([self.peripherals containsObject:peripheral])
    {
        
    }
    else
    {
        [self.peripherals addObject:peripheral];
        [self.peripheralTable reloadData];
    }
}


- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    self.connectedPeripheral = peripheral;
    self.connecting = NO;
    NSString *message = [NSString stringWithFormat:@"设备:%@", peripheral.name];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"连接成功"
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"ok", nil];
    [alert show];
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    self.connectedPeripheral = nil;
    self.connecting = NO;
    NSString *message = [NSString stringWithFormat:@"设备:%@", peripheral.name];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"连接失败"
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"ok", nil];
    [alert show];
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    self.connectedPeripheral = nil;
    self.connecting = NO;
    NSString *message = [NSString stringWithFormat:@"设备:%@", peripheral.name];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"连接断开"
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"ok", nil];
    [alert show];
}

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.peripherals.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"BluetoothCell";
    NSInteger row = [indexPath row];
    CBPeripheral *peripheral = self.peripherals[row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.textLabel.text = [NSString stringWithFormat:@"%@", peripheral.name];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", peripheral.identifier.UUIDString];
    
    return cell;
}

#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.connectedPeripheral)//断开
    {
        [self.manager cancelPeripheralConnection:self.connectedPeripheral];
    }
    else//链接
    {
        NSInteger row = [indexPath row];
        CBPeripheral *peripheral = self.peripherals[row];
        NSDictionary *options = @{CBConnectPeripheralOptionNotifyOnDisconnectionKey: @YES};
        [self.manager connectPeripheral:peripheral options:options];
        self.connecting = YES;
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
